package com.zbj.storm.wordcount;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.storm.spout.SpoutOutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichSpout;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Values;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * LineSpout
 *
 * @author weigang
 * @create 2019-09-04
 **/
public class LineSpout extends BaseRichSpout {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private SpoutOutputCollector collector;

    private List<String> lineList;

    private int index;

    private Map<UUID, Values> pending;

    @Override
    public void open(Map<String, Object> conf, TopologyContext context, SpoutOutputCollector collector) {
        this.collector = collector;
        pending = Maps.newConcurrentMap();
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader("test.txt"));
            lineList = Lists.newArrayList();
            String nextLine;
            while (StringUtils.isNotBlank(nextLine = bufferedReader.readLine())) {
                lineList.add(nextLine);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void nextTuple() {

        Values values = new Values(lineList.get(index));
        UUID msgId = UUID.randomUUID();
        pending.put(msgId, values);

        if (index < lineList.size()) {
            collector.emit(values, msgId);
            index++;
        } else {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //return;
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("line"));
    }

    @Override
    public void ack(Object msgId) {
        this.pending.remove(msgId);
        super.ack(msgId);
    }

    @Override
    public void fail(Object msgId) {
        logger.warn("数据发送失败了！应该重发这条数据！" + msgId + "-> " + lineList.get((int) msgId));
        //collector.emit(new Values(lineList.get((int) msgId)), msgId);
        collector.emit(this.pending.get(msgId), msgId);
    }
}